<template>
  <c-back-wrap :loading="loading" go-page="经销商门店业务变更" current-page="审核">
    <QupFormContainer :column="1">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="110px">
        <el-form-item prop="fileReviewResult" label="审批结果">
          <c-dict-select v-model="formData.fileReviewResult" dict-type-code="REVIEW_RESULT" clearable placeholder="审批结果" />
        </el-form-item>
        <el-form-item v-if="[2, '2'].includes(formData.fileReviewResult)" prop="assistToHandleAccount" label="协办用户" :span="24/4">
          <c-common-search-qup-person v-model="formData.assistToHandleAccount" :label.sync="formData.assistToHandleName" multiple placeholder="协办用户" />
        </el-form-item>
        <el-form-item prop="fileReviewAdvice" label="审批意见" :span="24">
          <el-input v-model="formData.fileReviewAdvice" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 3}" placeholder="审批意见" clearable />
        </el-form-item>
      </el-form>
    </QupFormContainer>

    <c-title v-if="[1,'1'].includes(formData.fileReviewResult)" title="经销商-客户业务类型变更信息">
      <CustomerBusinessTypeChange ref="customerBusinessTypeChange" v-model="businessTypeFormData" is-shop-change :detail="detail" :start-observe="startObserve" />
    </c-title>
    <c-title title="经销商-客户基本信息">
      <CusetomerBaseInfoView :detail="detail" />
    </c-title>
    <c-title title="经销商-选择待变更门店">
      <ChangeTable :table-data="changeResultTableData" type="view" />
    </c-title>
    <c-title title="经销商-门店业务类型变更信息">
      <!-- <el-collapse v-model="activeName"> -->
      <c-collapse-item v-for="(d,i) in changeResultTableData" :key="i" :name="i+1">
        <div slot="title" class="change-table-title">
          <span>{{ d.code }}</span>
          <span>{{ d.name }}</span>
          <span>{{ d.shopAddr }}</span>
        </div>
        <QupList :column="3" sep="：" default-value="" label-position="right" label-width="140">
          <QupListItem label="是否报图" :value="d.isReportPic" dict-type-code="BOOLEANS" :prop-enum="{domainCode:'marketing',appCode:'slm'}" :span="24" />
          <QupListItem label="成品面积" :value="`${d.endProductArea || 0}㎡`" />
          <QupListItem label="全屋定制面积" :value="`${d.fullHouseArea || 0}㎡`" />
          <QupListItem label="整体橱柜面积" :value="`${d.cabinetArea || 0}㎡`" />
          <QupListItem label="卫浴面积" :value="`${d.bathroomArea || 0}㎡`" />
          <QupListItem label="样板间面积" :value="`${d.modelRoomArea || 0}㎡`" />
          <QupListItem label="窗帘面积" :value="`${d.curtainArea || 0}㎡`" />
          <QupListItem label="橱柜套数" :value="d.cabinetSuite || 0" />
          <QupListItem label="卫浴套数" :value="d.bathroomSuite || 0" />
          <QupListItem label="单店总面积" :value="`${d.totalArea || 0}㎡`" />
          <QupListItem label="变更后经营业务类型" :value="d.afterBusinessTypeName" :span="24" />
          <QupListItem label="补充协议附件" :span="24">
            <c-file-list v-model="d.ACCESS065" :uploadable="editable" :editable="editable" direct-del :model-id="d.id" type-code="ACCESS065" />
            <!-- <c-file-list :uploadable="false" :editable="false" :model-id="d.id" view-type="list" type-code="ACCESS065" /> -->
          </QupListItem>
          <QupListItem label="特殊建档附件" :span="24">
            <c-file-list v-model="d.ACCESS067" :uploadable="editable" :editable="editable" direct-del tip="如未报图/未交保证金等情况，业务请示申请审核通过的流程附件" :model-id="d.id" type-code="ACCESS067" />
            <!-- <c-file-list :uploadable="false" :editable="false" :model-id="d.id" view-type="list" type-code="ACCESS067" /> -->
          </QupListItem>
        </QupList>
      </c-collapse-item>
      <!-- </el-collapse> -->
    </c-title>
    <c-title title="BPM审核信息">
      <QupList :column="3" sep="：" default-value="" label-position="right" label-width="140">
        <QupListItem label="变更进度" :value="detail.schedule" dict-type-code="CTM_CUS_ARCHIVE_CHANGE_PROGRESS" :prop-enum="{domainCode:'marketing',appCode:'slm'}" />
        <QupListItem :value="detail.createTime" label="申请时间" />
        <QupListItem :value="detail.applyNo" label="BPM单号" />
        <!-- <QupListItem label="办事处审批结果" :value="detail.officeReviewResult" dict-type-code="REVIEW_RESULT" :prop-enum="{domainCode:'marketing',appCode:'slm'}" /> -->
        <!-- <QupListItem :value="detail.officeReviewTime" label="办事处审批结束时间" /> -->
        <!-- <QupListItem :value="detail.officeReviewAdvice" label="办事处审批意见" :span="24" /> -->
        <!-- <QupListItem :value="detail.officeAccountingReviewAdvice" label="办事处会计处理意见" :span="24" /> -->
      </QupList>
      <Options :data="detail.opinionDTOS" />
    </c-title>
    <div class="btn-center">
      <c-button type="default" @click="handleCancel">取消</c-button>
      <c-button type="primary" @click="handleConfirm">提交</c-button>
    </div>
  </c-back-wrap>
</template>
<script>
import { shopBusinessDetail, shopBusinessAudit } from '@/api/channelTask2/shopChange'
import CusetomerBaseInfoView from '@/views/channelTask2/dealerMarketingInfo/archive/components/CustomerBaseInfoView'
import CustomerBusinessTypeChange from './CustomerBusinessTypeChange'
import Options from '../../components/Options'

import ChangeTable from '../../components/ChangeTable'
export default {
  name: 'Audit',
  components: {
    ChangeTable,
    CusetomerBaseInfoView,
    CustomerBusinessTypeChange,
    Options
  },
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      detail: {},
      loading: false,
      formData: {
        fileReviewResult: '',
        fileReviewAdvice: '',
        assistToHandleAccount: [],
        assistToHandleName: []
      },
      businessTypeFormData: {},
      startObserve: false,
      activeName: 1
    }
  },
  computed: {
    isEdit() {
      return !!this.id
    },
    formRules() {
      return {
        fileReviewResult: [{ required: true, message: '请选择审批结果', trigger: 'change' }],
        assistToHandleAccount: [{ required: true, validator: (r, v, c) => {
          if (!v || v.length === 0) {
            c(new Error('请选择协办用户'))
          } else {
            c()
          }
        }, trigger: 'change' }],
        fileReviewAdvice: [{ required: true, message: '请输入审批意见', trigger: 'change' }]
      }
    },
    changeTableData() {
      return this.detail.shopBusinessDTOS || []
    },
    changeResultTableData() {
      return this.changeTableData.filter(e => [1, '1'].includes(e.isChange))
    },
    editable() {
      return [1, '1'].includes(this.formData.fileReviewResult)
    }
  },
  created() {
    this.getDetailData().then(() => {
      setTimeout(() => {
        this.startObserve = true
      }, 200)
    })
  },
  methods: {
    getDetailData() {
      this.loading = true
      return shopBusinessDetail(this.id).then(res => {
        this.detail = res.data
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleCancel() {
      this.$pageStack.pop()
    },
    async validate() {
      await this.$refs.form.validate()
      if (this.editable) {
        if (this.$refs.customerBusinessTypeChange) {
          await this.$refs.customerBusinessTypeChange.validate()
        }
        const errMsg = []
        for (const f of this.changeResultTableData) {
          if (!f.ACCESS065 || !(f.ACCESS065 instanceof Array) || f.ACCESS065.length === 0) {
            errMsg.push(`${f.code}-${f.name}, 请上传补充协议附件!`)
          }
        }
        if (errMsg.length > 0) {
          this.$message({
            type: 'warning',
            dangerouslyUseHTMLString: true,
            message: `<div>${errMsg.join('<br>')}</div>`
          })
          return Promise.reject(false)
        }
      }
      return Promise.resolve(true)
    },
    getPostData() {
      const data = {
        ...this.formData,
        ...this.businessTypeFormData,
        id: this.id
      }
      if (data.afterBusinessTypeCode instanceof Array) {
        data.afterBusinessTypeCode = data.afterBusinessTypeCode.join(',')
        data.afterBusinessTypeName = data.afterBusinessTypeName.join(',')
      }
      data.attachmentDTOS = []
      this.changeResultTableData.forEach(e => {
        data.attachmentDTOS.push(...this.$getFiles(e.ACCESS065 || []), ...this.$getFiles(e.ACCESS067 || []))
      })
      // 处理协办用户
      if (data.assistToHandleAccount instanceof Array) {
        data.assistToHandleAccount = data.assistToHandleAccount.join('，')
        data.assistToHandleName = data.assistToHandleName.join('，')
      }
      return data
    },
    handleConfirm() {
      return this.validate().then(() => {
        return shopBusinessAudit(this.getPostData()).then(res => {
          this.$message.success('操作成功!')
          this.$pageStack.pop('onPage')
        })
      })
    },
    handleAuditFormChange(v) {
      // 同意不同意展示不同
    }
  }
}
</script>
<style lang="scss" scoped>
.change-table-title{
  display: flex;
  justify-content: flex-start;
  align-items: center;
  &>span{
    color: #333;
    font-size: 16px;
    font-weight: 600;
    margin-right: 10px;
  }
}
</style>
